#include <QMessageBox>
#include "newnode.h"
#include "ui_newnode.h"

NewNode::NewNode(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewNode)
{
    ui->setupUi(this);
}

NewNode::~NewNode()
{
    delete ui;
}

int NewNode::sub_node(int level, QList<Article> article_list) {
    int index = 0;
    for (Article a : article_list) {
        QString item_name;
        for (int i = 0; i < level; ++i) {
            item_name += "-";
        }
        item_name += " " + a.name;
        this->ui->in_article_combo_box->addItem(item_name);
        this->article[index].combo_index = index;
        ++index;
        index = this->sub_node(level + 1, a.article_list);
    }
    return index;
}

void NewNode::showEvent(QShowEvent*) {
    this->ui->in_article_combo_box->clear();
    this->ui->title_line_edit->setText("");
    this->ui->content_plain_text_edit->setPlainText("");
    int index = 0;
    for (Article a : this->article) {
        this->article[index].combo_index = index;
        ++index;
        this->ui->in_article_combo_box->addItem(a.name);
        index = this->sub_node(1, a.article_list);
    }
}

void NewNode::set_article_list(QList<Article> article) {
    this->article = article;
}

Article NewNode::article_at(int index, QList<Article> article) {
    Article ret;
    ret.type = -1;
    for (Article a : article) {
        if (a.combo_index == index) {
            return a;
        } else {
            ret = this->article_at(index, a.article_list);
            if (ret.type == 1) {
                return ret;
            }
        }
    }
    return ret;
}

void NewNode::on_save_button_clicked() {
    QString title = this->ui->title_line_edit->text();
    QString content = this->ui->content_plain_text_edit->toPlainText();
    if (title.contains('\'') || content.contains('\'')) {
        QMessageBox::warning(this, "System Warning", "title or content cannot contains '");
        return;
    }

    int index = this->ui->in_article_combo_box->currentIndex();
    if (index < 0) {
        QMessageBox::warning(this, "System Warning", "index is -1");
        return;
    }
    Article a = this->article_at(index, this->article);
    if (a.type == -1) {
        QMessageBox::warning(this, "System Warning", "Cannot find the item");
        return;
    }
    emit this->send_node(a.article_id, a.id, title, content);
    this->close();
}
